package com.lekang.service.impl;

import java.math.BigDecimal;
import java.util.List;

import com.lekang.mapper.BedMapper;
import com.lekang.mapper.RoomTypeMapper;
import com.lekang.domain.RoomType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.lekang.mapper.RoomMapper;
import com.lekang.domain.Room;
import com.lekang.service.IRoomService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 房间Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-21
 */
@Service
public class RoomServiceImpl implements IRoomService 
{
    @Autowired
    private RoomMapper roomMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private RoomTypeMapper roomTypeMapper;

    /**
     * 查询房间
     * 
     * @param id 房间主键
     * @return 房间
     */
    @Override
    public Room selectRoomById(Long id)
    {
        return roomMapper.selectRoomById(id);
    }

    /**
     * 查询房间列表
     * 
     * @param room 房间
     * @return 房间
     */
    @Override
    public List<Room> selectRoomList(Room room)
    {
        return roomMapper.selectRoomList(room);
    }

    /**
     * 新增房间
     * 
     * @param room 房间
     * @return 结果
     */
    @Override
    @Transactional
    public int insertRoom(Room room)
    {
        // 唯一性校验
        int count = roomMapper.countByFloorAndRoomNo(room.getFloorId(), room.getRoomNo());
        if (count > 0) {
            throw new RuntimeException("当前楼层下房间号已存在");
        }
        
        // 从房型表获取总床位数
        if (room.getRoomTypeId() != null) {
            RoomType roomType = roomTypeMapper.selectRoomTypeById(room.getRoomTypeId());
            if (roomType != null && roomType.getTotalBeds() != null) {
                room.setTotalBeds(roomType.getTotalBeds().longValue());
            } else {
                room.setTotalBeds(0L); // 如果房型未设置总床位数，默认为0
            }
        } else {
            room.setTotalBeds(0L);
        }
        
        // 初始化其他默认值
        if (room.getOccupiedBeds() == null) {
            room.setOccupiedBeds(0L);
        }
        if (room.getOccupancyRate() == null) {
            room.setOccupancyRate(BigDecimal.ZERO);
        }
        if (room.getIsDeleted() == null) {
            room.setIsDeleted(0L);
        }
        return roomMapper.insertRoom(room);
    }

    /**
     * 修改房间
     * 
     * @param room 房间
     * @return 结果
     */
    @Override
    @Transactional
    public int updateRoom(Room room)
    {
        // 校验：若修改了房间号或楼层ID，需检查唯一性
        Room oldRoom = selectRoomById(room.getId());
        if (oldRoom == null) {
            throw new RuntimeException("房间不存在");
        }
        // 只有当房间号或楼层ID发生变化时，才需要校验
        if (!oldRoom.getRoomNo().equals(room.getRoomNo()) || !oldRoom.getFloorId().equals(room.getFloorId())) {
            int count = roomMapper.countByFloorAndRoomNo(room.getFloorId(), room.getRoomNo());
            if (count > 0) {
                throw new RuntimeException("当前楼层下房间号已存在");
            }
        }
        return roomMapper.updateRoom(room);
    }

    /**
     * 批量删除房间
     * 
     * @param ids 需要删除的房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomByIds(Long[] ids)
    {
        return roomMapper.deleteRoomByIds(ids);
    }

    /**
     * 删除房间信息
     * 
     * @param id 房间主键
     * @return 结果
     */
    @Override
    public int deleteRoomById(Long id)
    {
        return roomMapper.deleteRoomById(id);
    }

    @Override
    public Room selectRoomWithBeds(Long id) {
        Room room = roomMapper.selectRoomWithBeds(id);
        if (room == null) {
            return null;
        }
        // 关键修复：处理totalBeds为null的情况，默认设为0L
        Long totalBeds = room.getTotalBeds();
        totalBeds = (totalBeds == null) ? 0L : totalBeds; // 新增这行

        // 统计入住床位数（处理null为0）
        Integer occupiedBeds = bedMapper.countOccupiedByRoomId(id);
        occupiedBeds = (occupiedBeds == null) ? 0 : occupiedBeds;

        // 计算入住率（此时totalBeds已确保不为null）
        BigDecimal occupancyRate = totalBeds > 0
                ? new BigDecimal(occupiedBeds)
                .divide(new BigDecimal(totalBeds), 2, BigDecimal.ROUND_HALF_UP)
                .multiply(new BigDecimal(100))
                : BigDecimal.ZERO;

        room.setOccupiedBeds(occupiedBeds.longValue());
        room.setOccupancyRate(occupancyRate);
        return room;
    }

    @Override
    public List<Room> selectRoomsWithBedsByFloorId(Long floorId) {
        return roomMapper.selectRoomsWithBedsByFloorId(floorId);
    }
}
